package com.vueblog.webapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vueblog.webapi.entity.BlogTagsEntity;
import com.vueblog.webapi.entity.TagEntity;
import com.vueblog.webapi.enums.ResponseEnum;
import com.vueblog.webapi.exception.BusinessException;
import com.vueblog.webapi.mapper.BlogTagsMapper;
import com.vueblog.webapi.mapper.TagMapper;
import com.vueblog.webapi.request.BasePageRequest;
import com.vueblog.webapi.request.CreateOrUpdateTagRequest;
import com.vueblog.webapi.response.BasePageResponse;
import com.vueblog.webapi.response.BaseResponse;
import com.vueblog.webapi.response.TagBlogCountResponse;
import com.vueblog.webapi.service.ITagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author luosj
 * @since 2021-05-15
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, TagEntity> implements ITagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private BlogTagsMapper blogTagsMapper;

    /**
     * 获取标签列表(分页模式)
     * @return
     */
    @Override
    public BasePageResponse getTagPageList(BasePageRequest request) {
        Page<HashMap<String, Object>> page = new Page<>(request.getPageNum(), request.getPageSize());
        List<HashMap<String, Object>> pageList = tagMapper.getTagPageList(page);
        page.setRecords(pageList);
        return new BasePageResponse<>(ResponseEnum.SUCCESS, (int) page.getTotal(), page.getRecords());
    }
    /**
     * 获取标签列表(下拉列表模式)
     */
    @Override
    public BaseResponse getTagList() {
        List<HashMap<String, Object>> list = tagMapper.getTagList();
        return new BaseResponse(ResponseEnum.SUCCESS,list);
    }

    /**
     * 创建标签
     * @param request
     * @return
     */
    @Override
    @Transactional
    public BaseResponse createTag(CreateOrUpdateTagRequest request) {
        // 判断标签是否存在
        beforeCreate(request);
        // 创建标签实体类
        TagEntity entity = new TagEntity();
        // 注入name值
        entity.setName(request.getName());
        if (tagMapper.insert(entity) > 0) {// 判断标签是否添加成功
            // 返回成功信息
            return new BaseResponse(ResponseEnum.SUCCESS);
        }else {
            // 返回失败信息
            return new BaseResponse(ResponseEnum.DATABASE_ERROR);
        }

    }

    // 判断标签是否存在
    private void beforeCreate(CreateOrUpdateTagRequest request) {
        Integer count = tagMapper.selectCount(new QueryWrapper<TagEntity>().lambda()
                .eq(TagEntity::getName, request.getName()));
        if (count > 0) {
            throw new BusinessException("该分类已存在");
        }
    }

    /**
     * 编辑标签
     */
    @Override
    @Transactional
    public BaseResponse updateTagInfo(CreateOrUpdateTagRequest request, String id) {
        // 判断标签是否存在并设置对象基本信息
        TagEntity entity = beforeUpdate(request, id);
        if (tagMapper.updateById(entity) > 0) {// 判断标签是否修改成功
            // 返回成功信息
            return new BaseResponse(ResponseEnum.SUCCESS);
        }else {
            // 返回失败信息
            return new BaseResponse(ResponseEnum.DATABASE_ERROR);
        }
    }

    private TagEntity beforeUpdate(CreateOrUpdateTagRequest request, String id) {
        TagEntity entity = tagMapper.selectById(id);
        if ( entity == null){
            throw new BusinessException("该分类不存在");
        }
        int count = this.count(new QueryWrapper<TagEntity>().lambda()
                .eq(TagEntity::getName, request.getName())
                .ne(TagEntity::getId, id));
        if (count > 0) {
            throw new BusinessException("该分类已存在");
        }else {
            entity.setName(request.getName());
        }
        return entity;
    }

    /**
     * 删除标签
     */
    @Override
    @Transactional
    public BaseResponse deleteTagInfo(String id) {
        // 删除标签
        int result = tagMapper.deleteById(id);
        if (result > 0) {// 判断标签是否删除
            // 删除博客标签中间表中tagId字段值为id的数据
            blogTagsMapper.delete(new QueryWrapper<BlogTagsEntity>().lambda()
                    .eq(BlogTagsEntity::getTagsId, id));
            // 返回成功信息
            return new BaseResponse(ResponseEnum.SUCCESS);
        }
        // 返回失败信息
        return new BaseResponse(ResponseEnum.ERROR);
    }

    /**
     * 根据博客查询标签
     */
    @Override
    public BaseResponse getTagByBlog(String blogId) {
        List<Long> list = tagMapper.getTagByBlog(blogId);
        return new BaseResponse(ResponseEnum.SUCCESS, list);
    }

    /**
     * 获取标签对应博客数量列表
     */
    @Override
    public BaseResponse getTagBlogCountList() {
        List<HashMap<String, Object>> tagList = tagMapper.getTagList();
        List<TagBlogCountResponse> tagBlogCountList = new ArrayList<>();
        if (tagList != null) {
            for (HashMap<String, Object> tag : tagList) {
                Integer count = blogTagsMapper.selectCount(new QueryWrapper<BlogTagsEntity>().lambda()
                        .eq(BlogTagsEntity::getTagsId, tag.get("tagId")));
                TagBlogCountResponse tagBlogCountResponse = new TagBlogCountResponse(
                        (Long) tag.get("tagId"), (String) tag.get("tagName"), count);
                tagBlogCountList.add(tagBlogCountResponse);
            }
        }
        // 根据count降序排序
        tagBlogCountList.sort((x, y) -> -Double.compare(x.getBlogCount(), y.getBlogCount()));
        return new BaseResponse(ResponseEnum.SUCCESS, tagBlogCountList);
    }
}
